<template>
  <div class="container">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="top" label-width="100px" class="tweets-form">
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="postForm.name" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="任务类型" prop="taskType">
            <el-select
              v-model="postForm.taskType"
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="计划时间" prop="planTime">
            <el-date-picker
              v-model="postForm.planTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择计划时间"
              style="width:100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="目标科室" prop="departids">
            <el-select
              v-model="postForm.departids"
              multiple
              filterable
              placeholder="可多选"
              style="width:100%"
            >
              <el-option
                v-for="item in deparpmentOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="相关产品（代表可见）" prop="brandids">
            <el-select
              v-model="postForm.brandids"
              multiple
              filterable
              placeholder="可多选"
              style="width:100%"
            >
              <el-option
                v-for="item in productsOptions"
                :key="item.id"
                :label="item.brand"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt30">
        <el-col :span="18" :offset="3">
          <el-form-item class="text-center">
            <el-button type="primary" @click="submitForm">下一步</el-button>
            <el-button @click="resetForm">重置</el-button>
            <el-divider v-if="isEditTask" direction="vertical" />
            <el-button
              v-if="isEditTask"
              type="warning"
              icon="el-icon-s-promotion"
              :loading="pushBtnLoading"
              :disabled="pushBtnLoading"
              @click="pushTweet"
            >推送任务</el-button>
            <el-divider v-if="isEditTask" direction="vertical" />
            <el-button
              v-if="isEditTask"
              type="danger"
              plain
              icon="el-icon-delete"
              @click="removeTweet"
            >删除任务</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  getTweetsList,
  addTweet,
  updateTweet,
  pushTweet,
  removeTweet
} from '@/api/tweets'
import {
  getDepartments,
  getProducts
} from '@/api/baseData'

const defaultForm = {
  id: undefined,
  name: '',
  taskType: '',
  planTime: '',
  clusterids: [],
  departids: [],
  brandids: [],
  mediaid: ''
}

export default {
  name: 'TweetTaskStep1',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      taskId: '',
      taskState: null,
      typeOptions: [
        {
          id: 0,
          name: '普通任务'
        },
        {
          id: 1,
          name: '定时任务'
        }
      ],
      deparpmentOptions: [],
      productsOptions: [],
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        name: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        taskType: [
          { required: true, message: '请选择任务类型', trigger: 'change' }
        ],
        planTime: [
          { required: true, message: '请选择计划时间', trigger: 'blur' }
        ]
        // clusterids: [
        //   { required: true, message: '请选择目标群组', trigger: 'change' }
        // ],
        // departids: [
        //   { required: true, message: '请选择目标科室', trigger: 'change' }
        // ]
      },
      pushBtnLoading: false
    }
  },
  computed: {
    isEditTask() {
      return this.taskState === 0 && this.isEdit
    }
  },
  created() {
    this.fetchDepartments()
    this.fetchProducts()
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.taskId = id
      this.fetchData(id)
    }
  },
  methods: {
    fetchDepartments() {
      getDepartments().then(response => {
        // console.log(response)
        this.deparpmentOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchProducts() {
      getProducts().then(response => {
        // console.log(response)
        this.productsOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchData(id) {
      getTweetsList({ id }).then(response => {
        const { data } = response
        // console.log(data)
        this.postForm.id = data.list[0].id
        this.postForm.name = data.list[0].name
        this.postForm.taskType = data.list[0].tasktype
        this.postForm.planTime = data.list[0].plantime
        this.postForm.departids = data.list[0].departids
        this.postForm.brandids = data.list[0].brandids
        this.postForm.mediaid = data.list[0].mediaid
        this.taskState = data.list[0].state
      }).catch(err => {
        console.log(err)
      })
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.postForm.departids = !this._.isEmpty(this.postForm.departids) ? this.postForm.departids.join(',') : ''
          this.postForm.brandids = !this._.isEmpty(this.postForm.brandids) ? this.postForm.brandids.join(',') : ''
          this.loading = true
          if (this.isEdit) {
            updateTweet(this.postForm).then(response => {
              // console.log(response)
              this.loading = false
              this.$router.push(`/tweets/edit/${this.taskId}?step=2`)
            }).catch(err => {
              console.log(err)
            })
          } else {
            addTweet(this.postForm).then(response => {
              // console.log(response)
              const { data } = response
              this.loading = false
              this.$router.push(`/tweets/edit/${data.id}?step=2`)
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.postForm.resetFields()
    },
    pushTweet() {
      this.$confirm('确定推送此任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.pushBtnLoading = true
        pushTweet({
          id: this.taskId
        }).then(response => {
          // console.log(response)
          this.$message({
            type: 'success',
            message: '推送任务成功!',
            duration: 5000
          })
          this.pushBtnLoading = false
          this.taskState = 1
        }).catch(err => {
          console.log(err)
          this.pushBtnLoading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消推送'
        })
      })
    },
    removeTweet() {
      this.$confirm('此操作将永久删除该任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeTweet({
          id: this.taskId
        }).then(response => {
          // console.log(response)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.$router.go(-1)
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 40px 140px;
}
</style>
